import axiosObj from "../../component/interceptor.js";
import alipay from '../../component/alipay.js';
import { createGlobalWebsocket, createdChatWebsocket } from "../../component/websocket.js";

new Vue({
    el: "#app",
    data: function () {
        return {
            userAvatar: '',
            userId: 0,
            searchKey: '',
            showAllGoods: true,
            goods: [],
            selectedGoods: {},
            total: 1000,
            pageSize: 12,
            pageNum: 1,
            shopCount: 1,
            chatVisible: false,
            // 聊天列表,  { key: sellerId(Number), value: { id: 1, name: '', avatar: ''} }
            chatList: new Map(),
            // 建立的通信对象
            golbalWebsocket: null,
            selectedChatSocket: null,
            // 输入消息
            inputMsg: '',
            sendBtnDisabled: true,
            // 选中的聊天窗口, 结构为 { id: 1, name: '', avatar: ''}
            selectedChat: null,
            // 聊天记录，结构为 { key: sellerId(Number), value: [ Message对象1, Message对象2 ] }
            chatHistory: new Map(),
            // 聊天窗口强制重新渲染
            refreshKey: Math.random()
        }
    },
    watch: {
        showAllGoods(val) {
            if (val) {
                this.fetchGoods();
            }
        },
        // 聊天输入框
        inputMsg(val) {
            if(val === '') {
                this.sendBtnDisabled = true;
            }
            else {
                this.sendBtnDisabled = false;
            }
        },
            // 监测 chatVisible 这个变量
        // chatVisible(newValue, oldValue) {
        //     // 当 chatVisible 变为 false 时执行特定的操作
        //     if (newValue === false) {
        //     if(this.selectedChatSocket) 
        //         this.selectedChatSocket.close();
        //     }
        // }
    },
    async created() {
        // 获取商品列表
        await this.fetchGoods();
        // 获取用户头像
        await this.getUserInfo();
        // 建立全局websocket
        this.golbalWebsocket =  createGlobalWebsocket(this.userId);
        this.golbalWebsocket.onmessage = this.globalMessage;
        this.get_all_chat();
    },
    beforeDestroy() {
        if(this.golbalWebsocket) this.golbalWebsocket.close();
        if(this.selectedChatSocket) this.selectedChatSocket.close();
    },
    methods: {
        // 获取用户头像和id
        async getUserInfo () {
            await axiosObj.get('/customer/address/getinfo')
                .then(({ data }) => {
                    if(data.code === 1000) {
                        let user = data.data.user;
                        this.userAvatar = user.avatar;
                        this.userId = user.id;
                    }
                })
                .catch(err => {
                    console.log('getUserInfo:', err);
                })
        },
        get_all_chat(){
            axiosObj({
                method: "post",
                url: "/websocket/ids1",
            })
                .then(({ data }) => {
                    if(data.code === 1000) {
                        console.log(data.data);
                        data.data.forEach(async(id) => {
                            console.log(id);
                            await this.getSenderInfo(id);
                        })
                    }
                })
        },
        // 全局信息提醒
        globalMessage({ data }) {
            console.log('Message push: ', data);
            // 消息加入消息池中， chaList 结构 { key: sellerId, value: { id: 111, name: '', avatar: '' } }
            // 这里存储的是全局websocket接收到的消息发送者的列表，这样用户打开Messages就能看到发送了消息的商家
            const data_array = JSON.parse(data);
            data_array.forEach(async({ senderId }, index) => {
                // 若商家之前不再用户的聊天列表中，就去获取商家的头像、名字等信息
                if (!this.chatList.get(senderId)) {
                    await this.getSenderInfo(senderId);
                };
                // 右上角消息提醒
                this.$notify({
                    title: 'New Message',
                    message: `You have a message from ${this.chatList.get(senderId).name}`,
                    offset: index * 75,
                    duration: 6000
                });
            });
        },
        // 获取聊天对象信息，并添加在 chatList 中
        async getSenderInfo(sellerId) {
            // 由于 ws 送达的消息只有 id 字段，所以需要再次请求获取发送方的头像店铺名等信息
            await axiosObj({
                method: "get",
                url: "/seller/search/information",
                params: {
                    Id: sellerId
                }
            })
                .then(({ data }) => {
                    if(data.code === 1000) {
                        this.chatList.set(sellerId, data.data);
                    }
                })
        },
        //跳转到聊天窗口
        openChat() {
            this.chatVisible = true;
        },
        // 选择指定聊天窗口，建立一对一通信
        selectChat(chat) {
            // 重复选择同一聊天，不进行任何操作
            if (this.selectedChat && chat.id === this.selectedChat.id) return;

            // 将上一个通信连接关闭
            if (this.selectedChat !== null) {
                let prevItem = document.getElementById(this.selectedChat.id);
                prevItem.classList.remove('selected-chat');
                this.selectedChatSocket.close();
            };

            // 建立新通信
            this.selectedChat = chat;
            let item = document.getElementById(chat.id);
            item.classList.add('selected-chat');
            this.selectedChatSocket = createdChatWebsocket(chat, this.userId);

            // 根据连接状态判断
            if (this.selectedChatSocket.readyState === 3 || this.selectedChatSocket.readyState === 2) {
                this.chatVisible = false;
                this.sendBtnDisabled = true;
                this.$message({
                    message: 'Get message failed, please check the network, or try again later',
                    type: 'warning'
                });
            }
            else {
                // 存储聊天信息
                if (!this.chatHistory.get(chat.id)) {
                    this.chatHistory.set(chat.id, []);
                };
                // 挂载消息处理函数
                this.selectedChatSocket.onmessage = this.receiveMessage;
                // 挂载通信关闭处理函数
                this.selectedChatSocket.onclose = this.closeChat;
            };
        },
        // 发送聊天消息
        sendMessage() {
            console.log('sendMessage: ', this.inputMsg);
            // 检查连接状态
            if(this.selectedChatSocket.readyState === 2 || this.selectedChatSocket.readyState === 3) {
                this.$message({
                    message: 'Please check the network, or try again later',
                    type: 'warning'
                });
            }
            else {
                this.selectedChatSocket.send(this.inputMsg);
                this.inputMsg = '';
            }
        },
        // 获取聊天窗口消息
        receiveMessage(event) {
            const data = JSON.parse(event.data);
            console.log('receiveMessage: ', data);
            // 具体聊天内容，即 message 类型
            if (data.type === 'message') {
                let sellerId = this.selectedChat.id;
                let chatHistory = this.chatHistory.get(sellerId);
                this.chatHistory.set(sellerId, chatHistory.concat(data.messages));
                console.log('ChatHistory: ', this.chatHistory.get(sellerId));
                this.refreshKey = Math.random();
            };
            // 自动滚动到底部
            this.$nextTick(() => {
                this.scrollTop();
            });
        },
        // 关闭聊天窗口
        closeChat() {
            // 清除聊天缓存
            this.chatHistory.set(this.selectedChat.id, []);
        },
        // 联系商家
        async contactSeller(sellerId) {
            // 获取商家信息
            await this.getSenderInfo(sellerId);
            // 打开聊天窗口
            this.openChat();
            // 选中聊天
            this.$nextTick(() => {
                this.selectChat(this.chatList.get(sellerId));
            });
        },
        // 聊天窗口自动滑动到底部
        scrollTop () {
            const chatLines = document.getElementsByClassName('chat-lines') || null;
            const innerContent = document.getElementsByClassName('chat-one-line-container') || null;
            if (chatLines && innerContent) {
                chatLines[0].scrollTo(0, innerContent[0].scrollHeight);
            };
        },
        // 聊天消息时间格式化
        formatDate (secs) {
            let time = (new Date(secs)).toLocaleTimeString('it-IT');
            return `${time.slice(0, 2)}:${time.slice(3, 5)}`;
        },
        // 获取商品列表
        async fetchGoods() {
            let params = {
                keyword: this.searchKey ? this.searchKey : undefined,
                pageNum: this.pageNum,
                pageSize: this.pageSize
            };
            await axiosObj({
                method: "get",
                url: "/customer/home/page",
                params,
            })
                .then(({ data: { data, code, msg } }) => {
                    if (code === 1000) {
                        if (data.data.length === 0) {
                            this.$message.warning('No luck finding that item!')
                        }
                        else {
                            this.total = data.total;
                            this.goods = data.data;
                        }
                    }
                    else if (code === 1001) {
                        this.$message.error('Seems like something went wrong.Please try again later!')
                    }
                    else {
                        this.$message.error(msg)
                    }
                })
                .catch((e) => {
                    console.log(e);
                })
        },
        // 跳转到购物车
        gotoShoppingCart() {
            window.location.href = '/buyer/cart';
        },
        // 跳转到我的账户
        gotoMine() {
            window.location.href = '/buyer/cart';
        },
        // 切换商品列表页
        async handlePageChange(currPage) {
            this.pageNum = currPage;
            await this.fetchGoods();
        },
        // 搜索框点击查询
        async searchSubmit() {
            this.showAllGoods = true;
            await this.fetchGoods();
        },
        // 查看商品详情
        async showDetails(id) {
            await axiosObj({
                method: "get",
                url: "/customer/product/getById",
                params: { id }
            })
                .then(({ data: { data, code, msg } }) => {
                    if (code === 1000) {
                        this.selectedGoods = data;
                        this.showAllGoods = false;
                    }
                    else if (code === 1001) {
                        this.$message.error('Product Not Exists!')
                    }
                    else {
                        this.$message.error(msg)
                    }
                })
                .catch((e) => {
                    console.log(e);
                })
        },
        // 立即购买
        async buyNow() {
            await axiosObj({
                method: "post",
                url: "/customer/admitOrder",
                data: [
                    {
                        number: this.shopCount,
                        productId: this.selectedGoods.id
                    }
                ]
            })
                .then(({ data: { code, msg, data } }) => {
                    if (code === 1000) {
                        this.$message.success('Purchase Successful!');
                        this.showAllGoods = true;
                        const orderid = data[0].id;
                        // alipay([orderid], this.selectedGoods.price);
                    }
                    else {
                        this.$message.error(msg);
                    }
                })
                .catch((e) => {
                    console.log(e);
                })
        },
        // 加入购物车
        async addToCart() {
            await axiosObj({
                method: "post",
                url: "/customer/product/addCart",
                params: {
                    number: this.shopCount,
                    productId: this.selectedGoods.id
                }
            })
                .then(({ data: { code } }) => {
                    if (code === 1000) {
                        this.$message.success('Added to Cart!')
                    }
                    else {
                        this.$message.error('Adding to cart failed. Please try again!')
                    }
                })
                .catch((e) => {
                    console.log(e);
                })
        },
        // 返回商品列表
        backToList() {
            this.showAllGoods = true;
        }
    }

})